<template>
    <view class="pages">
        <custom-bar customHeader ref="customBar" :headerHeight="30">
            <template #header>
                <view class="custom_bar_header">
                    <u--input
                        placeholder="搜索课程老师等关键字"
                        :customStyle="SearchInputStyle"
                        prefixIcon="search"
                        placeholderClass="search_placeholder"
                        prefixIconStyle="font-size: 22px;color:#b3b3b3"
                    ></u--input>
                </view>
            </template>
        </custom-bar>
        <view class="header">
            <u-swiper
                previousMargin="60"
                nextMargin="60"
                radius="5"
                bgColor="#ffffff"
                :list="list"
                height="280"
                keyName="url"
                showTitle
                circular
            ></u-swiper>
        </view>
        <view class="body">
            <u-divider></u-divider>
            <u-button @click="toCategory" type="success" throttleTime="1000">课程分类</u-button>
            <u-divider></u-divider>
            <u-button @click="downLoad" type="primary" :disabled="progress != 100" throttleTime="1000">{{
                progress == 100 ? '下载文件' : `下载中:${100}%`
            }}</u-button>
            <u-divider></u-divider>
            <u-button @click="downtimeFunc" type="info" :disabled="countTime > 0" throttleTime="1000"
                >倒计时{{ countTime > 0 ? downTime : '1分钟' }}</u-button
            >
            <u-divider></u-divider>
            <u-button @click="handlerDownTimeTask" type="info" :disabled="times.countTime > 0" throttleTime="1000"
                >开始倒计时任务{{ times.countTime > 0 ? times.downTime : '1分钟' }}</u-button
            >
            <u-divider></u-divider>
            <u-button @click="handlerClearTimeTask" type="error" throttleTime="1000">取消倒计时任务</u-button>
            <u-divider></u-divider>
            <u-button @click="handlerLoginOut" type="warning" throttleTime="1000">退出登录</u-button>
        </view>
    </view>
</template>

<script lang="ts">
import {Component, Vue, Mixins} from 'vue-property-decorator';
import CountDown from '@/common/mixins/countdown';
import {WebSocket, DownTime} from '@/utils';
import {UserModule} from '@/store/modules/user';
@Component({
    components: {},
})
export default class home extends Mixins(CountDown) {
    public list: Array<object | string>;
    public progress: number;
    public timeProxy: any;
    public timeTask: any = new DownTime();
    public times: any = {};
    constructor() {
        super();
        this.progress = 100;
        this.list = [
            {
                url: 'https://cdn.uviewui.com/uview/resources/video.mp4',
                title: '昨夜星辰昨夜风，画楼西畔桂堂东',
                poster: 'https://cdn.uviewui.com/uview/swiper/swiper1.png',
                type: 'video',
            },
            {
                url: 'https://cdn.uviewui.com/uview/swiper/swiper2.png',
                title: '身无彩凤双飞翼，心有灵犀一点通',
                type: 'image',
            },
            {
                url: 'https://cdn.uviewui.com/uview/swiper/swiper3.png',
                title: '谁念西风独自凉，萧萧黄叶闭疏窗，沉思往事立残阳',
            },
        ];
    }

    get SearchInputStyle(): object {
        // 默认值30px 对应组件headerHeight
        const height = 30 / (uni.upx2px(100) / 100);
        let style: any = {
            height: height + 'rpx',
            background: '#F5F5F5',
            borderRadius: '27rpx',
            width: '422rpx',
            padding: '0 6rpx',
        };
        // 以下代码不包含app h5 飞书
        // #ifndef APP-PLUS || H5 || MP-LARK
        this.$nextTick(() => {
            if (this.$refs.customBar) {
                // px转rpx
                const rpxHeight = (this.$refs.customBar as any).menuButtonInfo.height / (uni.upx2px(100) / 100);
                style.height = parseInt(rpxHeight.toString());
            }
        });
        // #endif
        return style;
    }
    get loadProgress(): number {
        return this.progress;
    }

    created() {
        // (this as any).$api.login({ name: "ztf" }).then((res: any) => {
        //   console.log("res", res);
        // });
    }

    handlerClearTimeTask() {
        this.timeTask.taskEnd(this.timeProxy);
    }
    // 使用倒计时任务开始倒计时
    handlerDownTimeTask() {
        const taskOptions: any = {
            key: 'test1',
            downTime: '00：00' as any,
            countTime: 0 as any,
            timerID: null as any,
        };
        this.timeProxy = new Proxy(taskOptions, {
            set: (target, prop, val, receiver) => {
                console.log('set', prop, val);
                this.times = receiver;
                return Reflect.set(target, prop, val, receiver);
            },
        });
        this.timeTask.startTask(this.timeProxy, 60);
    }

    downLoad() {
        this.progress = 0;
        (this as any).$api
            .downloadTest({url: '/file/test'}, (downloadTask: UniNamespace.DownloadTask) => {
                console.log('progress', downloadTask);
                downloadTask.onProgressUpdate((res: any) => {
                    this.progress = res.progress;
                    console.log('下载进度' + res.progress);
                    console.log('已经下载的数据长度' + res.totalBytesWritten);
                    console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
                    // 满足测试条件，取消下载任务。
                    // if (res.progress > 50) {
                    //   downloadTask.abort();
                    // }
                });
            })
            .then((res: any) => {
                console.log('res', res);
            })
            .catch((err: any) => {
                console.log('err', err);
            });
    }

    mounted() {
        this.createSocket();
    }
    async createSocket() {
        const webSocket = new WebSocket({
            url: 'wss://',
            name: 'message',
        });
        // 创建任务
        try {
            await webSocket.createTask();
            const message = webSocket.getStockTask('message');
            message.onMessage(this.onMassage);
            message.send(this.send());
            message.onOpen();
            message.onClose();
            message.onError();
        } catch (e) {
            console.log('webStock:error', e);
        }
        // 取消任务
        const res = await webSocket.cleanTask('message');
    }

    // 发送消息
    send(): object {
        const sendOptions = {
            data: '哈哈' as string | ArrayBuffer,
            success: (res: any) => {
                console.log('sendSuccess', res);
            },
            fail: (error: any) => {
                console.log('sendError', error);
            },
        };
        return sendOptions;
    }

    // 接受消息
    onMassage(data: string | ArrayBuffer) {
        console.log('接收到的消息', data);
    }

    downtimeFunc() {
        const time = 1 * 60;
        this.downTimeStart(time);
    }

    // 跳转课程分类
    toCategory(): void {
        console.log('toCategory');
        uni.navigateTo({
            url: '/pagesCourse/category/index',
        });
    }

    // 退出登录
    handlerLoginOut() {
        UserModule.LoginOut();
    }
}
</script>

<style lang="scss" scoped>
v-deep.pages {
    .search_placeholder {
        font-size: 24rpx;
        font-family: SourceHanSansCN;
        font-weight: 400;
        color: #b3b3b3;
        line-height: 15rpx;
    }
}
.pages {
    display: flex;
    flex-direction: column;
    width: 100%;
    min-height: 100vh;
    background: #f0f0f0;
    .custom_bar_header {
        width: 100%;
        height: 100%;
        padding: 0 28rpx;
    }
    .header {
        padding: 28rpx 0;
        height: auto;
        background: #ffffff;
    }
    .body {
        padding: 28rpx;
    }
}
</style>
